import { reactive, toRefs, unref } from 'vue'

/**
 * @param {Promise} fetchList
 * @param params 除page和limit外额外传递的字段
 */
export function useList(fetchList, params = {}) {
  // 统一状态管理
  const state = reactive({
    page: 1,
    limit: 10,
    list: [],
    /** more | loading | nomore */
    loadStatus: 'nomore'
  })

  async function getList() {
    try {
      const query = genQuery()
	  console.log(query)
      return await fetchList(query)
    } catch (e) {
      state.loadStatus = 'nomore'
    }
  }

  /**
   * 获取第一页的数据
   */
  async function getFirstList() {
    state.page = 1
    await getList().then(res => (state.list = res))
  }

  /**
   * 获取更多页的数据
   */
  async function getMoreList(status='more') {
	  state.loadStatus = status
	  console.log('+++++++++++++++++',state.loadStatus)
    if (state.loadStatus === 'more') {
      state.loadStatus = 'loading'
      state.page++
      await getList().then(res => {
        state.list = [].concat(state.list, res)
        state.loadStatus = res.length === state.limit ? 'more' : 'nomore'
      })
    }
  }

  /**
   * 生成传递的字段
   */
  function genQuery() {
    const query = {
      page: state.page,
      limit: state.limit,
      ...unref(params)
    }
    return query
  }
  function setState(status){
	  state.loadStatus = status
  }

  return {
    getFirstList,
    getMoreList,
    ...toRefs(state),
	setState
  }
}
